import { Page } from 'puppeteer';
import { IVideoMeta } from './videometa';
import { IUserBasic } from './_base';

const URL_MSG_AT = 'https://api.bilibili.com/x/msgfeed/at';

interface AtItem {
    id: number;
    user: {
        mid: number;
        fans: number;
        nickname: string;
        avatar: string;
        mid_link: string;
        follow: boolean;
    };
    item: {
        type: string;
        business: string;
        business_id: number;
        title: string;
        image: string;
        uri: string;
        subject_id: number;
        root_id: number;
        target_id: number;
        source_id: number;
        source_content: string;
        native_uri: string;
        at_details: any[];
        topic_details: any[];
        hide_reply_button: boolean;
    };
    at_time: number;
}

export class AT implements AtItem {
    constructor(public id: number, public user: {
        mid: number;
        fans: number;
        nickname: string;
        avatar: string;
        mid_link: string;
        follow: boolean;
    }, public item: {
        type: string;
        business: string;
        business_id: number;
        title: string;
        image: string;
        uri: string;
        subject_id: number;
        root_id: number;
        target_id: number;
        source_id: number;
        source_content: string;
        native_uri: string;
        at_details: any[];
        topic_details: any[];
        hide_reply_button: boolean;
    }, public at_time: number) {
    }

    AV() {
        return this.item.subject_id;
    }

    BV() {
        return this.item.uri.substring("https://www.bilibili.com/video/".length);
    }

    commentId() {
        return this.item.source_id;
    }

    timestamp() {
        return this.at_time;
    }

    userbasic(): IUserBasic {
        return {
            uid: this.user.mid,
            nickname: this.user.nickname,
            avatar: this.user.avatar,
            fans: this.user.fans,
        }
    }
}

export async function fetchNewAts(page: Page): Promise<AT[]> {
    const response = await page.goto(URL_MSG_AT);
    const rawData = await response?.json() as {
        code: number;
        message: string;
        ttl: number;
        data: {
            cursor: {
                is_end: boolean;
                id: number;
                time: number;
            }
            items: AtItem[];
        };
    };
    // console.log(rawData.data.items);
    return rawData.data.items.map((item) => new AT(item.id, item.user, item.item, item.at_time));
}